<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${pageTitle ?: '同步平台 - 数据库同步'}">同步平台 - 数据库同步</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar Navigation -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/}">
                                <i class="bi bi-house"></i> 首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/dashboard}">
                                <i class="bi bi-speedometer2"></i> 仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/server}">
                                <i class="bi bi-server"></i> 服务器管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/database}">
                                <i class="bi bi-database"></i> 数据库管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" th:href="@{/sync/database}">
                                <i class="bi bi-arrow-left-right"></i> 数据库同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/file}">
                                <i class="bi bi-files"></i> 文件同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/restore}">
                                <i class="bi bi-arrow-counterclockwise"></i> 数据库恢复
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/task/log}">
                                <i class="bi bi-list-check"></i> 同步日志
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">数据库同步</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button id="refreshScheduledTasks" class="btn btn-sm btn-outline-secondary me-2">
                            <i class="bi bi-arrow-clockwise"></i> 刷新定时任务
                        </button>
                        <a th:href="@{/sync/database/add}" class="btn btn-sm btn-primary">
                            <i class="bi bi-plus-circle"></i> 添加同步任务
                        </a>
                    </div>
                </div>
                
                <!-- Scheduled Tasks Status -->
                <div id="scheduledTasksStatus" class="alert alert-info mb-3" style="display: none;">
                    <h5><i class="bi bi-clock"></i> 当前活动的定时任务</h5>
                    <div id="scheduledTasksList">
                        <p>加载中...</p>
                    </div>
                </div>
                
                <!-- Database Sync Tasks List -->
                <div class="card">
                    <div class="card-body">
                        <div th:if="${tasks == null || tasks.empty}" class="alert alert-info">
                            <i class="bi bi-info-circle"></i> 您还没有创建任何数据库同步任务，请点击右上角的"添加同步任务"按钮创建。
                        </div>
                        
                        <!-- Tasks Table -->
                        <div th:if="${tasks != null && !tasks.empty}" class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>任务名称</th>
                                        <th>源数据库</th>
                                        <th>目标数据库</th>
                                        <th>定时任务</th>
                                        <th>状态</th>
                                        <th>上次执行</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr th:each="task : ${tasks}">
                                        <td>
                                            <span th:text="${task.name}">任务名称</span>
                                        </td>
                                        <td>
                                            <span th:each="db : ${databases}" th:if="${db.id == task.sourceId}" th:text="${db.name}">源数据库</span>
                                        </td>
                                        <td>
                                            <span th:each="db : ${databases}" th:if="${db.id == task.targetId}" th:text="${db.name}">目标数据库</span>
                                        </td>
                                        <td>
                                            <div th:if="${task.cronExpression != null && !task.cronExpression.empty}" 
                                                  class="d-flex align-items-center">
                                                <span th:text="${task.cronExpression}" class="badge bg-info me-1">
                                                    Cron表达式
                                                </span>
                                                <a href="#" class="cron-info-btn ms-1" data-bs-toggle="tooltip" title="查看定时详情">
                                                    <i class="bi bi-info-circle"></i>
                                                </a>
                                                <a href="#" class="cron-edit-btn ms-1" th:data-id="${task.id}" data-bs-toggle="tooltip" title="设置定时规则">
                                                    <i class="bi bi-clock"></i>
                                                </a>
                                            </div>
                                            <div th:if="${task.cronExpression == null || task.cronExpression.empty}" 
                                                  class="d-flex align-items-center">
                                                <span class="badge bg-secondary me-1">未设置</span>
                                                <a href="#" class="cron-edit-btn ms-1" th:data-id="${task.id}" data-bs-toggle="tooltip" title="设置定时规则">
                                                    <i class="bi bi-clock"></i>
                                                </a>
                                            </div>
                                        </td>
                                        <td>
                                            <span th:if="${task.status == 1}" class="badge bg-success">启用</span>
                                            <span th:if="${task.status == 0}" class="badge bg-danger">禁用</span>
                                        </td>
                                        <td>
                                            <div th:if="${task.lastExecutionTime != null}">
                                                <small th:text="${#temporals.format(task.lastExecutionTime, 'yyyy-MM-dd HH:mm:ss')}">
                                                    2023-01-01 12:00:00
                                                </small>
                                                <br/>
                                                <span th:if="${task.lastExecutionResult == 1}" class="badge bg-success">成功</span>
                                                <span th:if="${task.lastExecutionResult == 0}" class="badge bg-danger">失败</span>
                                            </div>
                                            <span th:if="${task.lastExecutionTime == null}" class="badge bg-secondary">从未执行</span>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a th:href="@{/sync/database/edit/{id}(id=${task.id})}" class="btn btn-outline-primary">
                                                    <i class="bi bi-pencil"></i> 编辑
                                                </a>
                                                <button type="button" class="btn btn-outline-success execute-btn"
                                                        th:data-id="${task.id}" th:data-name="${task.name}">
                                                    <i class="bi bi-play"></i> 执行
                                                </button>
                                                <button type="button" class="btn btn-outline-secondary status-btn"
                                                        th:data-id="${task.id}" th:data-status="${task.status}">
                                                    <i th:class="${task.status == 1 ? 'bi bi-pause' : 'bi bi-play'}"></i>
                                                    <span th:text="${task.status == 1 ? '禁用' : '启用'}">切换状态</span>
                                                </button>
                                                <button type="button" class="btn btn-outline-danger delete-btn"
                                                        th:data-id="${task.id}" th:data-name="${task.name}">
                                                    <i class="bi bi-trash"></i> 删除
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Task Info Cards -->
                        <div th:if="${tasks == null || tasks.empty}" class="row mt-4">
                            <div class="col-md-6">
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">创建数据库同步任务</h5>
                                    </div>
                                    <div class="card-body">
                                        <p>您需要先配置源数据库和目标数据库，然后才能创建同步任务。</p>
                                        <div class="d-grid gap-2">
                                            <a th:href="@{/database}" class="btn btn-outline-primary">
                                                <i class="bi bi-database"></i> 管理数据库
                                            </a>
                                            <a th:href="@{/sync/database/add}" class="btn btn-primary">
                                                <i class="bi bi-plus-circle"></i> 创建同步任务
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">同步配置说明</h5>
                                    </div>
                                    <div class="card-body">
                                        <ul class="list-group list-group-flush">
                                            <li class="list-group-item">支持不同类型数据库之间的数据同步</li>
                                            <li class="list-group-item">可以选择同步整个数据库或特定表</li>
                                            <li class="list-group-item">支持字段映射配置</li>
                                            <li class="list-group-item">支持数据转换和过滤</li>
                                            <li class="list-group-item">支持定时任务自动同步</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.3/dist/jquery.min.js"></script>
    <script th:src="@{/js/script.js}"></script>
    
    <!-- Task Execution Modal -->
    <div class="modal fade" id="executeModal" tabindex="-1" aria-labelledby="executeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="executeModalLabel">执行同步任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>确认要立即执行同步任务 <strong id="executeTaskName"></strong> 吗？</p>
                    <div id="executeResult" class="mt-3" style="display: none;">
                        <div class="spinner-border text-primary" role="status" id="executeSpinner">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <div id="executeMessage" class="alert mt-2" style="display: none;"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmExecute">执行</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Status Change Modal -->
    <div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="statusModalLabel">修改任务状态</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p id="statusConfirmText">确认要更改任务状态吗？</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmStatus">确认</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Delete Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">删除同步任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>确认要删除同步任务 <strong id="deleteTaskName"></strong> 吗？此操作不可撤销。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDelete">删除</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Cron Expression Info Modal -->
    <div class="modal fade" id="cronInfoModal" tabindex="-1" aria-labelledby="cronInfoModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="cronInfoModalLabel">定时任务表达式说明</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <h6>当前表达式：<span id="currentCronExpression" class="badge bg-primary"></span></h6>
                        <div id="cronDescription" class="alert alert-info"></div>
                    </div>
                    
                    <div class="mb-3">
                        <h6>Cron表达式格式：</h6>
                        <pre>秒 分 时 日 月 星期</pre>
                        <p>例如：<code>0 0 2 * * ?</code> 表示每天凌晨2点执行</p>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>表达式示例</th>
                                    <th>说明</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><code>0 0 * * * ?</code></td>
                                    <td>每小时执行一次（整点执行）</td>
                                </tr>
                                <tr>
                                    <td><code>0 0 0/12 * * ?</code></td>
                                    <td>每12小时执行一次</td>
                                </tr>
                                <tr>
                                    <td><code>0 0 0 * * ?</code></td>
                                    <td>每天凌晨执行一次</td>
                                </tr>
                                <tr>
                                    <td><code>0 0 12 * * ?</code></td>
                                    <td>每天中午12点执行一次</td>
                                </tr>
                                <tr>
                                    <td><code>0 0 0 ? * MON</code></td>
                                    <td>每周一凌晨执行一次</td>
                                </tr>
                                <tr>
                                    <td><code>0 0 0 1 * ?</code></td>
                                    <td>每月1号凌晨执行一次</td>
                                </tr>
                                <tr>
                                    <td><code>0 0/30 * * * ?</code></td>
                                    <td>每30分钟执行一次</td>
                                </tr>
                                <tr>
                                    <td><code>0 0 9-18 * * ?</code></td>
                                    <td>工作时间（早9点到晚6点）每小时执行一次</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Cron Expression Edit Modal -->
    <div class="modal fade" id="cronEditModal" tabindex="-1" aria-labelledby="cronEditModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="cronEditModalLabel">设置定时任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="cronForm">
                        <input type="hidden" id="taskId" name="taskId">
                        
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="enableCron" name="enableCron">
                            <label class="form-check-label" for="enableCron">
                                启用定时任务
                            </label>
                        </div>
                        
                        <div id="cronSettings" style="display: none;">
                            <div class="mb-3">
                                <label class="form-label">快速选择常用定时：</label>
                                <div class="d-flex flex-wrap gap-2">
                                    <button type="button" class="btn btn-sm btn-outline-primary cron-preset" data-cron="0 0 * * * ?">
                                        每小时
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-primary cron-preset" data-cron="0 0 0/12 * * ?">
                                        每12小时
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-primary cron-preset" data-cron="0 0 0 * * ?">
                                        每天凌晨
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-primary cron-preset" data-cron="0 0 12 * * ?">
                                        每天中午
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-primary cron-preset" data-cron="0 0 0 ? * MON">
                                        每周一
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-primary cron-preset" data-cron="0 0 0 1 * ?">
                                        每月1号
                                    </button>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="cronExpression" class="form-label">Cron表达式：</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="cronExpression" name="cronExpression" 
                                           placeholder="例如：0 0 0 * * ? （每天凌晨执行）">
                                    <button class="btn btn-outline-secondary" type="button" id="cronHelp">
                                        <i class="bi bi-question-circle"></i>
                                    </button>
                                </div>
                                <div class="form-text">格式：秒 分 时 日 月 星期</div>
                            </div>
                            
                            <div class="alert alert-info" id="cronExpressionDescription"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveCron">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <script th:inline="javascript">
        $(document).ready(function() {
            // Get context path from Thymeleaf
            const contextPath = /*[[@{/}]]*/ '';
            
            // Execute Task
            $('.execute-btn').on('click', function() {
                const taskId = $(this).data('id');
                const taskName = $(this).data('name');
                
                $('#executeTaskName').text(taskName);
                $('#executeResult').hide();
                $('#executeMessage').hide().removeClass('alert-success alert-danger');
                $('#executeSpinner').show();
                $('#confirmExecute').show();
                $('#executeModal').modal('show');
                
                $('#confirmExecute').off('click').on('click', function() {
                    // Show spinner
                    $('#executeResult').show();
                    $('#confirmExecute').prop('disabled', true);
                    
                    // Execute task
                    $.ajax({
                        url: contextPath + 'sync/database/' + taskId + '/execute',
                        type: 'POST',
                        success: function(response) {
                            $('#executeSpinner').hide();
                            $('#executeMessage').show();
                            
                            if (response.success) {
                                $('#executeMessage')
                                    .addClass('alert-success')
                                    .html('<i class="bi bi-check-circle"></i> 任务执行成功！');
                                
                                // Append task details if available
                                if (response.data) {
                                    let details = '<div class="mt-2">';
                                    
                                    if (response.data.totalRows !== undefined) {
                                        details += '<p><strong>同步总行数:</strong> ' + response.data.totalRows + '</p>';
                                    }
                                    
                                    if (response.data.tableCount !== undefined) {
                                        details += '<p><strong>同步总表数:</strong> ' + response.data.tableCount + '</p>';
                                    }
                                    
                                    if (response.data.tableRowCounts) {
                                        details += '<p><strong>各表同步行数:</strong></p>';
                                        details += '<ul class="list-group">';
                                        for (const [table, count] of Object.entries(response.data.tableRowCounts)) {
                                            details += '<li class="list-group-item d-flex justify-content-between align-items-center">' +
                                                table + 
                                                '<span class="badge bg-primary rounded-pill">' + count + ' 行</span></li>';
                                        }
                                        details += '</ul>';
                                    }
                                    
                                    if (response.data.failedTables && response.data.failedTables.length > 0) {
                                        details += '<p><strong>同步失败表:</strong></p>';
                                        details += '<ul class="list-group">';
                                        for (const table of response.data.failedTables) {
                                            details += '<li class="list-group-item list-group-item-danger">' + table + '</li>';
                                        }
                                        details += '</ul>';
                                    }
                                    
                                    details += '</div>';
                                    $('#executeMessage').append(details);
                                }
                                
                                // Hide confirm button and auto-refresh after delay
                                $('#confirmExecute').hide();
                                setTimeout(function() {
                                    window.location.reload();
                                }, 3000);
                            } else {
                                $('#executeMessage')
                                    .addClass('alert-danger')
                                    .html('<i class="bi bi-x-circle"></i> 任务执行失败: ' + response.message);
                                
                                // Re-enable button
                                $('#confirmExecute').prop('disabled', false);
                            }
                        },
                        error: function(xhr, status, error) {
                            $('#executeSpinner').hide();
                            $('#executeMessage')
                                .show()
                                .addClass('alert-danger')
                                .html('<i class="bi bi-x-circle"></i> 请求失败: ' + error);
                            
                            // Re-enable button
                            $('#confirmExecute').prop('disabled', false);
                        }
                    });
                });
            });
            
            // Change Task Status
            $('.status-btn').on('click', function() {
                const taskId = $(this).data('id');
                const currentStatus = $(this).data('status');
                const newStatus = currentStatus === 1 ? 0 : 1;
                const statusText = newStatus === 1 ? '启用' : '禁用';
                
                $('#statusConfirmText').text('确认要' + statusText + '该同步任务吗？');
                $('#statusModal').modal('show');
                
                $('#confirmStatus').off('click').on('click', function() {
                    $.ajax({
                        url: contextPath + 'sync/database/' + taskId + '/status',
                        type: 'PUT',
                        data: { status: newStatus },
                        success: function(response) {
                            if (response.success) {
                                window.location.reload();
                            } else {
                                alert('修改状态失败: ' + response.message);
                            }
                        },
                        error: function() {
                            alert('请求失败，请稍后再试');
                        },
                        complete: function() {
                            $('#statusModal').modal('hide');
                        }
                    });
                });
            });
            
            // Delete Task
            $('.delete-btn').on('click', function() {
                const taskId = $(this).data('id');
                const taskName = $(this).data('name');
                
                $('#deleteTaskName').text(taskName);
                $('#deleteModal').modal('show');
                
                $('#confirmDelete').off('click').on('click', function() {
                    $.ajax({
                        url: contextPath + 'sync/database/' + taskId,
                        type: 'DELETE',
                        success: function(response) {
                            if (response.success) {
                                window.location.reload();
                            } else {
                                alert('删除失败: ' + response.message);
                            }
                        },
                        error: function() {
                            alert('请求失败，请稍后再试');
                        },
                        complete: function() {
                            $('#deleteModal').modal('hide');
                        }
                    });
                });
            });
            
            // Cron Expression Info Modal
            $('.cron-info-btn').on('click', function(e) {
                e.preventDefault();
                const cronExpression = $(this).closest('td').find('.badge').text().trim();
                $('#currentCronExpression').text(cronExpression);
                
                // 解析cron表达式并显示人类可读的描述
                const cronParts = cronExpression.split(' ');
                let description = '该任务将';
                
                if (cronExpression === '0 0 0 * * ?') {
                    description += '每天凌晨0点执行';
                } else if (cronExpression === '0 0 0/12 * * ?') {
                    description += '每12小时执行一次（凌晨0点和中午12点）';
                } else if (cronExpression === '0 0 * * * ?') {
                    description += '每小时（整点）执行一次';
                } else if (cronExpression.match(/0 0 0 \? \* [A-Z]{3}/)) {
                    const day = cronExpression.substring(cronExpression.lastIndexOf(' ') + 1);
                    const days = {
                        'MON': '周一', 'TUE': '周二', 'WED': '周三', 
                        'THU': '周四', 'FRI': '周五', 'SAT': '周六', 'SUN': '周日'
                    };
                    description += `每${days[day] || day}凌晨0点执行`;
                } else if (cronExpression === '0 0 0 1 * ?') {
                    description += '每月1号凌晨0点执行';
                } else {
                    description += '按照指定的cron表达式执行，时间为：';
                    if (cronParts[0] === '0' && cronParts[1] === '0') {
                        if (cronParts[2].includes('/')) {
                            const interval = cronParts[2].split('/')[1];
                            description += `每${interval}小时执行一次`;
                        } else if (cronParts[2] === '*') {
                            description += '每小时整点执行';
                        } else if (cronParts[2].includes('-')) {
                            const range = cronParts[2].split('-');
                            description += `每天${range[0]}点到${range[1]}点之间的每个整点执行`;
                        } else {
                            description += `每天${cronParts[2]}点整执行`;
                        }
                    } else if (cronParts[1].includes('/')) {
                        const interval = cronParts[1].split('/')[1];
                        description += `每${interval}分钟执行一次`;
                    } else {
                        description += `每天${cronParts[2]}点${cronParts[1]}分${cronParts[0]}秒执行`;
                    }
                }
                
                $('#cronDescription').text(description);
                $('#cronInfoModal').modal('show');
            });
            
            // 初始化工具提示
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
            
            // Edit Cron Expression
            $('.cron-edit-btn').on('click', function(e) {
                e.preventDefault();
                const taskId = $(this).data('id');
                const cronExpression = $(this).closest('td').find('.badge').text().trim();
                
                $('#taskId').val(taskId);
                $('#enableCron').prop('checked', cronExpression !== '未设置');
                $('#cronExpression').val(cronExpression !== '未设置' ? cronExpression : '');
                
                // 显示或隐藏cron设置
                if ($('#enableCron').is(':checked')) {
                    $('#cronSettings').show();
                    updateCronDescription($('#cronExpression').val());
                } else {
                    $('#cronSettings').hide();
                }
                
                $('#cronEditModal').modal('show');
            });
            
            // 显示/隐藏cron设置
            $('#enableCron').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#cronSettings').slideDown();
                    updateCronDescription($('#cronExpression').val());
                } else {
                    $('#cronSettings').slideUp();
                }
            });
            
            // 快速选择cron表达式
            $('.cron-preset').on('click', function() {
                const cronExpression = $(this).data('cron');
                $('#cronExpression').val(cronExpression);
                updateCronDescription(cronExpression);
            });
            
            // 更新cron表达式描述
            $('#cronExpression').on('input', function() {
                updateCronDescription($(this).val());
            });
            
            // 显示cron帮助
            $('#cronHelp').on('click', function() {
                $('#cronInfoModal').modal('show');
            });
            
            // 保存cron表达式
            $('#saveCron').on('click', function() {
                const taskId = $('#taskId').val();
                const enableCron = $('#enableCron').is(':checked');
                const cronExpression = enableCron ? $('#cronExpression').val() : '';
                
                if (enableCron && !cronExpression) {
                    alert('请输入有效的Cron表达式');
                    return;
                }
                
                $.ajax({
                    url: contextPath + 'sync/database/' + taskId + '/cron',
                    type: 'PUT',
                    data: { cronExpression: cronExpression },
                    success: function(response) {
                        if (response.success) {
                            window.location.reload();
                        } else {
                            alert('保存失败: ' + response.message);
                        }
                    },
                    error: function() {
                        alert('请求失败，请稍后再试');
                    },
                    complete: function() {
                        $('#cronEditModal').modal('hide');
                    }
                });
            });
            
            // 解析并显示cron表达式描述
            function updateCronDescription(cronExpression) {
                if (!cronExpression) {
                    $('#cronExpressionDescription').text('请输入或选择一个Cron表达式');
                    return;
                }
                
                const cronParts = cronExpression.split(' ');
                if (cronParts.length !== 6) {
                    $('#cronExpressionDescription').text('无效的Cron表达式格式，应包含6个部分');
                    return;
                }
                
                let description = '该任务将';
                
                if (cronExpression === '0 0 0 * * ?') {
                    description += '每天凌晨0点执行';
                } else if (cronExpression === '0 0 0/12 * * ?') {
                    description += '每12小时执行一次（凌晨0点和中午12点）';
                } else if (cronExpression === '0 0 * * * ?') {
                    description += '每小时（整点）执行一次';
                } else if (cronExpression.match(/0 0 0 \? \* [A-Z]{3}/)) {
                    const day = cronExpression.substring(cronExpression.lastIndexOf(' ') + 1);
                    const days = {
                        'MON': '周一', 'TUE': '周二', 'WED': '周三', 
                        'THU': '周四', 'FRI': '周五', 'SAT': '周六', 'SUN': '周日'
                    };
                    description += `每${days[day] || day}凌晨0点执行`;
                } else if (cronExpression === '0 0 0 1 * ?') {
                    description += '每月1号凌晨0点执行';
                } else {
                    description += '按照指定的cron表达式执行，时间为：';
                    if (cronParts[0] === '0' && cronParts[1] === '0') {
                        if (cronParts[2].includes('/')) {
                            const interval = cronParts[2].split('/')[1];
                            description += `每${interval}小时执行一次`;
                        } else if (cronParts[2] === '*') {
                            description += '每小时整点执行';
                        } else if (cronParts[2].includes('-')) {
                            const range = cronParts[2].split('-');
                            description += `每天${range[0]}点到${range[1]}点之间的每个整点执行`;
                        } else {
                            description += `每天${cronParts[2]}点整执行`;
                        }
                    } else if (cronParts[1].includes('/')) {
                        const interval = cronParts[1].split('/')[1];
                        description += `每${interval}分钟执行一次`;
                    } else {
                        description += `每天${cronParts[2]}点${cronParts[1]}分${cronParts[0]}秒执行`;
                    }
                }
                
                $('#cronExpressionDescription').text(description);
            }
            
            // 刷新定时任务状态
            function refreshScheduledTasks() {
                $.ajax({
                    url: contextPath + 'sync/database/scheduled',
                    type: 'GET',
                    success: function(response) {
                        if (response.success && response.data) {
                            const tasks = response.data;
                            $('#scheduledTasksStatus').show();
                            
                            if (tasks.length === 0) {
                                $('#scheduledTasksList').html('<p>当前没有运行中的定时任务</p>');
                            } else {
                                let html = '<ul class="list-group">';
                                tasks.forEach(function(task) {
                                    html += '<li class="list-group-item d-flex align-items-center">';
                                    html += '<i class="bi bi-clock-history text-success me-2"></i>';
                                    html += '<span>' + task + '</span>';
                                    html += '</li>';
                                });
                                html += '</ul>';
                                $('#scheduledTasksList').html(html);
                            }
                        } else {
                            $('#scheduledTasksList').html('<p class="text-danger">获取定时任务状态失败</p>');
                        }
                    },
                    error: function() {
                        $('#scheduledTasksStatus').show();
                        $('#scheduledTasksList').html('<p class="text-danger">获取定时任务状态失败，请稍后再试</p>');
                    }
                });
            }
            
            // 页面加载时刷新定时任务状态
            refreshScheduledTasks();
            
            // 点击刷新按钮
            $('#refreshScheduledTasks').on('click', function() {
                $('#scheduledTasksList').html('<p>加载中...</p>');
                refreshScheduledTasks();
            });
        });
    </script>
</body>
</html> 